package com.fuze.utils;

import com.fuze.common.constant.FileType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author sepc_
 * @date 4/20/2021 14:34
 */
@Slf4j
public class CheckFileUtils {


    /**
     * 二进制转化为16进制
     */
    private static String bytes2hex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte aByte : bytes) {
            String temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                hex.append("0");
            }
            hex.append(temp.toLowerCase());
        }
        return hex.toString();
    }

    /**
     * 读取文件头
     */
    public static String getFileHeader(InputStream inputStream) {
        byte[] b = new byte[28];
        //这里需要注意的是,每个文件的magic word的长度都不相同,因此需要使用startWith() 判断
        try {
            int read = inputStream.read(b, 0, 28);
            if (read != b.length) {
                log.debug("读取的图片头部字节长度不匹配！");
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("获取图片文件的文件头失败，错误信息：{}", e.getMessage(), e);
        }
        return bytes2hex(b);
    }

    public static boolean check(String fileHead) {
        if (fileHead == null || fileHead.length() == 0) {
            return false;
        }
        fileHead = fileHead.toUpperCase();
        FileType[] fileTypes = FileType.values();
        for (FileType type : fileTypes) {
            if (fileHead.startsWith(type.getValue())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 测试方法
     *
     * @param args 可变参数
     * @throws IOException IO异常
     */
    public static void main(String[] args) throws IOException {
        String path = "D:\\sepc_\\Desktop\\Snipaste_2021-04-20_14-45-15.png";
        FileInputStream is = new FileInputStream(path);
        String header = CheckFileUtils.getFileHeader(is);
        boolean check = CheckFileUtils.check(header);
        System.out.println("check = " + check);
    }

    /**
     * 获取文件后缀
     *
     * @param image 图片文件
     * @return 文件后缀
     */
    public static Optional<String> getSuffix(MultipartFile image) {
        String originalFilename = image.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return Optional.empty();
        }
        int index = originalFilename.lastIndexOf(".");
        if (index < 0) {
            return Optional.empty();
        }
        return Optional.of(originalFilename.substring(index));
    }
}

